﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FCDB.Entity;

namespace FCDB.Repository
{
    public class IDCreateLogic : LogicBase, ILogic
    {
        public static readonly  int IDStartSeeding=1000;
        public static Object obj = new Object();

        public static long GenerateID(string idName, string description, int seed = 1000)
        {
            IDCreateLogic logic = new IDCreateLogic();
            long num = logic.GetNewID(idName, description, seed);
            return num;
        }

       private long GetNewID(string idName, string description, int seed=1000)
       {
           var log = new FB.Services.LoggingService();
           var logger = log.GetAccessLogger();
           try
           {
               //lock (obj)
               //{

               var connStr = ObjectContextHelper.GetEntityConnectionString();
               using (var foa = new FCDBEntities(connStr))
               {

                   //IDCreater id = DBHelper.IDCreater.FirstOrDefault(t => t.IDName == idName);
                   IDCreater id = foa.IDCreater.Where(w => w.IDName == idName).FirstOrDefault();

                   if (id == null)
                   {
                       IDCreater idCreater = new IDCreater()
                       {
                           CreateTime = DateTime.Now,
                           CurrentCount = seed,
                           Description = description,
                           IDName = idName
                       };
                       //this.Add(idCreater);
                       id = foa.IDCreater.Add(idCreater);
                       //id = idCreater;                  
                   }
                   else
                   {
                       id.CurrentCount = id.CurrentCount + 1;

                       foa.IDCreater.Attach(id);
                       var entry = foa.Entry(id);
                       entry.Property(e => e.CurrentCount).IsModified = true;
                       //foa.Entry<IDCreater>(id).State = System.Data.Entity.EntityState.Modified;
                       //this.Update(id);
                   }

                   foa.SaveChanges();
                   return (long)id.CurrentCount;

                   //}
               }
           }
           catch (Exception ex)
           {
               throw ex;
               logger.ErrorException(ex.Message, ex);
           }

       }
    }
}
